import axios from 'axios'
import { Message } from 'element-ui';
import router from '../router/index'
import { isTokenExpired } from './jwt';

// 创建 axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout: 5000,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 用于存储pending的请求
const pendingRequests = new Map()

// 生成请求的唯一key
const generateRequestKey = (config) => {
  const { url, method, params, data } = config
  return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
}

// 取消所有pending的请求
const cancelPendingRequests = () => {
  pendingRequests.forEach((cancel) => {
    cancel()
  })
  pendingRequests.clear()
}

//请求拦截器
service.interceptors.request.use((config) => {
  // 为请求创建取消令牌
  config.cancelToken = new axios.CancelToken((cancel) => {
    const requestKey = generateRequestKey(config)
    pendingRequests.set(requestKey, cancel)
  })

  //如果存在token，请求携带token
  if(window.sessionStorage.getItem('token')){
    if (!isTokenExpired(window.sessionStorage.getItem('token'))) {
      config.headers['token'] = window.sessionStorage.getItem('token');
    }
  }
  return config;
}, (error) => {
  Message.error({ message: error });
  return Promise.reject(error);
})

// api接口 响应成功 / 响应失败 【响应拦截器】
//后端提供：响应码，响应信息，对象
service.interceptors.response.use((success) => {
  // 从pendingRequests中移除已完成的请求
  const requestKey = generateRequestKey(success.config)
  pendingRequests.delete(requestKey)

  if (success.status && success.status === 200) {
    // 直接返回整个响应数据，包含 result、message 和 data
    return success.data
  } else {
    Message.error({ message: success.message })
    return Promise.reject(success.message)
  }
}, (error) => {
  // 从pendingRequests中移除已完成的请求
  if (error.config) {
    const requestKey = generateRequestKey(error.config)
    pendingRequests.delete(requestKey)
  }

  if (error.response) {
    if (error.response.status === 401) {
      // 取消所有pending的请求
      cancelPendingRequests()
      // 清除token
      window.sessionStorage.removeItem('token')
      Message.error({ message: '请登录账号' })
      // 跳转到登录页
      router.replace('/login')
      return Promise.reject(error)
    } else if (error.response.status === 504 || error.response.status === 404) {
      Message.error({ message: '服务器被吃了( ╯□╰ )' })
    } else if (error.response.status === 403) {
      Message.error({ message: '权限不足，请联系管理员' })
    } else {
      if (error.response.data.message) {
        Message.error({ message: error.response.data.message })
      } else {
        Message.error({ message: '未知错误' })
      }
    }
  }
  return Promise.reject(error)
})

//封装请求
//post
let base = '';
export const postRequest = (url, params) => {
   return service({
      method: 'post',
      url: `${base}${url}`,
      data: params
   })
};

//put
export const putRequest = (url, params) => {
   return service({
      method: 'put',
      url: `${base}${url}`,
      data: params
   })
};

//get
export const getRequest = (url, params) => {
   return service({
      method: 'get',
      url: `${base}${url}`,
      data: params
   })
};

//del
export const deleteRequest = (url, params) => {
   return service({
      method: 'delete',
      url: `${base}${url}`,
      data: params
   })
};

export default service

